package com.atlin.project.controller.task;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.domain.task.UserTasks;
import com.atlin.project.model.dto.userTasks.UserTasksAddRequest;
import com.atlin.project.model.dto.userTasks.UserTasksEditRequest;
import com.atlin.project.model.dto.userTasks.UserTasksQueryRequest;
import com.atlin.project.model.dto.userTasks.UserTasksUpdateRequest;
import com.atlin.project.model.enums.task.UserTaskPriorityEnum;
import com.atlin.project.model.enums.task.UserTaskStatusEnum;
import com.atlin.project.model.vo.UserTasksVO;
import com.atlin.project.model.vo.task.UserTaskCommonVO;
import com.atlin.project.service.SysUserService;
import com.atlin.project.service.task.UserTasksService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 任务接口
 *
 * @author atlin
 */
@RestController
@RequestMapping("/userTasks")
public class UserTasksController {

    @Resource
    private UserTasksService userTasksService;

    @Resource
    private SysUserService sysUserService;

    // region 增删改查

    /**
     * 创建
     *
     * @param userTasksAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserTasks(@RequestBody UserTasksAddRequest userTasksAddRequest, HttpServletRequest request) {
        if (userTasksAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);

        Long result = userTasksService.createUserTask(userTasksAddRequest, loginUser);

        return ResultUtils.success(result);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserTasks(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserTasks olduserTasks = userTasksService.getById(id);
        ThrowUtils.throwIf(olduserTasks == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可删除
        // todo
        boolean b = userTasksService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param userTasksUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserTasks(@RequestBody UserTasksUpdateRequest userTasksUpdateRequest) {
        if (userTasksUpdateRequest == null || userTasksUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserTasks userTasks = new UserTasks();
        BeanUtils.copyProperties(userTasksUpdateRequest, userTasks);

        // 参数校验
        userTasksService.validAndFill(userTasks, false);
        long id = userTasksUpdateRequest.getId();
        // 判断是否存在
        UserTasks olduserTasks = userTasksService.getById(id);
        ThrowUtils.throwIf(olduserTasks == null, ErrorCode.NULL_ERROR);
        // todo other operation

        boolean result = userTasksService.updateById(userTasks);
        return ResultUtils.success(result);
    }

    /**
     * 修改任务信息
     *
     * @param userTasksEditRequest
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editUserTasks(@RequestBody UserTasksEditRequest userTasksEditRequest, HttpServletRequest request) {
        if (userTasksEditRequest == null || userTasksEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserTasks userTasks = new UserTasks();
        BeanUtils.copyProperties(userTasksEditRequest, userTasks);

        // 参数校验
        userTasksService.validAndFill(userTasks, false);
        long id = userTasksEditRequest.getId();
        // 判断是否存在
        UserTasks olduserTasks = userTasksService.getById(id);
        ThrowUtils.throwIf(olduserTasks == null, ErrorCode.NULL_ERROR);

        boolean result = userTasksService.updateById(userTasks);


        SysUser loginUser = sysUserService.getLoginUser(request);
        boolean res =  userTasksService.editUserTask(userTasksEditRequest, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<UserTasks> getUserTasksById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserTasks userTasks = userTasksService.getById(id);
        if (userTasks == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        // todo
        return ResultUtils.success(userTasks);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserTasksVO> getUserTasksVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserTasks userTasks = userTasksService.getById(id);
        if (userTasks == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        UserTasksVO userTasksVO = UserTasksVO.objToVo(userTasks);
        return ResultUtils.success(userTasksVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param userTasksQueryRequest 查询参数
     * @param request               查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserTasksVO>> listUserTasksVOByPage(@RequestBody UserTasksQueryRequest userTasksQueryRequest,
                                                                 HttpServletRequest request) {
        long current = userTasksQueryRequest.getCurrent();
        long size = userTasksQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<UserTasks> userTasksPage = userTasksService.page(new Page<>(current, size),
                userTasksService.getQueryWrapper(userTasksQueryRequest));

        Page<UserTasksVO> userTasksVOPage = userTasksService.getUserTasksVOPage(userTasksPage, request);

        return ResultUtils.success(userTasksVOPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param userTasksQueryRequest 查询参数
     * @param request               查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo/space")
    public BaseResponse<Page<UserTasksVO>> listUserTasksVOPage(@RequestBody UserTasksQueryRequest userTasksQueryRequest,
                                                               HttpServletRequest request) {
        long current = userTasksQueryRequest.getCurrent();
        long size = userTasksQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<UserTasksVO> userTasksVOPage = userTasksService.getMyUserTasksVOPage(userTasksQueryRequest);

        return ResultUtils.success(userTasksVOPage);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param userTasksQueryRequest 查询参数
     * @param request               查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserTasks>> listUserTasksByPage(@RequestBody UserTasksQueryRequest userTasksQueryRequest,
                                                             HttpServletRequest request) {
        long current = userTasksQueryRequest.getCurrent();
        long size = userTasksQueryRequest.getPageSize();
        Page<UserTasks> userTasksPage = userTasksService.page(new Page<>(current, size),
                userTasksService.getQueryWrapper(userTasksQueryRequest));
        return ResultUtils.success(userTasksPage);
    }

    // endregion

    // region 任务基础信息

    /**
     * 获取任务清单状态枚举列表
     *
     * @return 任务清单状态枚举
     */
    @GetMapping("/getUserTaskStatusList")
    public BaseResponse<List<UserTaskCommonVO>> getUserTaskStatusList() {

        ArrayList<UserTaskCommonVO> res = new ArrayList<>();
        for (UserTaskStatusEnum userTaskStatusEnum : UserTaskStatusEnum.values()) {
            UserTaskCommonVO userTaskCommonVO = new UserTaskCommonVO();
            BeanUtils.copyProperties(userTaskStatusEnum, userTaskCommonVO);
            res.add(userTaskCommonVO);
        }

        return ResultUtils.success(res);
    }

    /**
     * 获取任务优先级枚举列表
     *
     * @return 任务清单优先级枚举
     */
    @GetMapping("/getUserTaskPriorityList")
    public BaseResponse<List<UserTaskCommonVO>> getUserTaskPriorityList() {

        ArrayList<UserTaskCommonVO> res = new ArrayList<>();
        for (UserTaskPriorityEnum userTaskPriorityEnum : UserTaskPriorityEnum.values()) {
            UserTaskCommonVO userTaskCommonVO = new UserTaskCommonVO();
            BeanUtils.copyProperties(userTaskPriorityEnum, userTaskCommonVO);
            res.add(userTaskCommonVO);
        }

        return ResultUtils.success(res);
    }

    // endregion
}
